#pragma once

#include <set>
#include "msli/entities/Point.hpp"
#include "msli/entities/Reference.hpp"
#include "msli/index/HuffmanTree.hpp"
#include "msli/common/CalCirclePos.h"

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 上层节点类
template<typename T>
class UpperNode {
public:
    std::vector<UpperEntry<T>> upperEntries;

    UpperNode() = default;

    // 带参数的构造函数,允许初始化upperEntries
    explicit UpperNode(const std::vector<UpperEntry<T>> &initialEntries) : upperEntries(initialEntries) {}

    // 析构函数
    ~UpperNode() { upperEntries.clear(); }
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 底层节点类
template<typename T>
class BottomNode {
public:
    std::vector<BottomEntry<T>> bottomEntries;

    BottomNode() = default;

    // 带参数的构造函数,允许初始化upperEntries
    explicit BottomNode(const std::vector<BottomEntry<T>> &initialEntries) : bottomEntries(initialEntries) {}

    // 析构函数
    ~BottomNode() { bottomEntries.clear(); }
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 两层索引结构类
template<typename T>
class TwoLayerIndex {
public:
    UpperNode<T> upper;
    BottomNode<T> bottom;
private:

//    // 计算节点与相邻节点的重叠面积
//    double calculateOverlapArea(const BottomEntry<T> &node, const std::vector<BottomEntry<T>> &adjacentNodes);
//
//    // 获取节点的相邻节点
//    std::vector<BottomEntry<T>> getAdjacentNodes(const BottomEntry<T> &node);

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 执行节点扩展操作
//    void expandNode(BottomEntry<T> &node) {
//
//        node.objects.reserve(node.objects.size() + m);
//    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 执行节点分裂操作
//    void splitNode(BottomEntry<T> &node) {
//
//        int splitNum = 2;
//        std::vector<BottomEntry<T>> newNodes;
//        for (int i = 0; i < splitNum; ++i) {
//
//            BottomEntry<T> newEntry({}, 0, {});
//            newNodes.push_back(newEntry);
//        }
//
//        auto it = std::find(bottom.bottomEntries.begin(), bottom.bottomEntries.end(), node);
//        if (it != bottom.bottomEntries.end()) {
//            bottom.bottomEntries.erase(it);
//            bottom.bottomEntries.insert(bottom.bottomEntries.end(), newNodes.begin(), newNodes.end());
//        }
//    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//    void updateUpperNodes() {
//
//        for (auto &upperEntry: upper.upperEntries) {
//            std::vector<DIS_TYPE> newDistances;
//            for (auto &bottomEntry: upperEntry.bottomEntryByMinDisToPivot) {
//                newDistances.push_back(calculateDistance(upperEntry.pivotPoint, bottomEntry->clusterCenter));
//            }
//            upperEntry.dis = newDistances;
//
//        }
//    }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public:
    // 插入函数
//    void insert(const Point<T> &insertPoint) {
//
//        std::vector<std::pair<T, UpperEntry<T> *>> pivotDistances;
//        for (auto &upperEntry: upper.upperEntries) {
//            T dist = calculateDistance(insertPoint, upperEntry.pivotPoint);
//            pivotDistances.push_back(std::make_pair(dist, &upperEntry));
//        }
//        std::sort(pivotDistances.begin(), pivotDistances.end(), [](const auto &p1, const auto &p2) {
//            return p1.first < p2.first;
//        });
//
//
//        std::vector<std::pair<T, BottomEntry<T> *>> possibleBottomEntries;
//        for (auto &pivotDist: pivotDistances) {
//            UpperEntry<T> *upperEntry = pivotDist.second;
//
//            for (auto &bottomEntry: upperEntry->bottomEntryByMinDisToPivot) {
//                possibleBottomEntries.push_back(
//                        std::make_pair(calculateDistance(insertPoint, bottomEntry->clusterCenter), bottomEntry));
//            }
//        }
//        std::sort(possibleBottomEntries.begin(), possibleBottomEntries.end(), [](const auto &p1, const auto &p2) {
//            return p1.first < p2.first;
//        });
//
//
//        bool inserted = false;
//        for (auto &bottomEntryDist: possibleBottomEntries) {
//            if (bottomEntryDist.first < bottomEntryDist.second->radius) {
//
//                bottomEntryDist.second->objects.push_back(insertPoint);
//                inserted = true;
//                break;
//            }
//        }
//
//        if (!inserted) {
//
//            auto nearestEntry = std::min_element(possibleBottomEntries.begin(), possibleBottomEntries.end(),
//                                                 [](const auto &p1, const auto &p2) {
//                                                     return p1.first < p2.first;
//                                                 });
//            nearestEntry->second->objects.push_back(insertPoint);
//        }
//
//        for (auto &bottomEntry: bottom.bottomEntries) {
//
//            double density =
//                    (double) bottomEntry.objects.size() / (3.141592653589793 * bottomEntry.radius * bottomEntry.radius);
//            if (density > delta1) {
//
//                double overlapArea = calculateOverlapArea(bottomEntry, getAdjacentNodes(bottomEntry));
//                if (overlapArea < delta2) {
//
//                    expandNode(bottomEntry);
//                } else {
//
//                    splitNode(bottomEntry);
//                }
//            }
//        }
//
//        updateUpperNodes();
//    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 执行 kNN 查询
    std::vector<OID_TYPE> kNNQuery(Point<T> &queryPoint, int k, int lk) {
        std::vector<OID_TYPE> result;
        // 存储查询点到所有簇的距离
        std::vector<std::pair<DIS_TYPE, BottomEntry<T> *>> disToCluCenter;

        for (auto &bottomEntry: bottom.bottomEntries) {
            DIS_TYPE dist = queryPoint.distance(bottomEntry.clusterCenter);
            disToCluCenter.push_back(std::make_pair(dist, &bottomEntry));
        }

        // 按照距离从小到大排序
        std::sort(disToCluCenter.begin(), disToCluCenter.end(), [](const auto &p1, const auto &p2) {
            return p1.first < p2.first;
        });

        // 初始半径，取最近簇的距离
        DIS_TYPE radius = disToCluCenter[0].first;
        int index = 0;
        bool found = false;
        std::vector<std::pair<DIS_TYPE, OID_TYPE>> kNNRangeAns;

        while (!found) {
            if (disToCluCenter[index].second->objects.size() > lk) {

                radius = ((double) (lk - 1) / lk) * radius;
                bottomKNNQuery(queryPoint, radius, kNNRangeAns, *disToCluCenter[index].second);

                if (kNNRangeAns.size() >= k) {
                    found = true;
                    std::sort(kNNRangeAns.begin(), kNNRangeAns.end(), [](const auto &p1, const auto &p2) {
                        return p1.first < p2.first;
                    });

                    for (int i = 0; i < k; ++i) {
                        result.push_back(kNNRangeAns[i].second);
                    }
                } else {
                    index++;
                    radius = disToCluCenter[index].first;
                }
            } else if (disToCluCenter[index].second->objects.size() >= k) {
//                std::cout << "------------******************************--------------" << std::endl;

                bottomKNNQuery(queryPoint, radius, kNNRangeAns, *disToCluCenter[index].second);

                if (kNNRangeAns.size() >= k) {
                    found = true;
                    std::sort(kNNRangeAns.begin(), kNNRangeAns.end(), [](const auto &p1, const auto &p2) {
                        return p1.first < p2.first;
                    });

                    for (int i = 0; i < k; ++i) {
                        result.push_back(kNNRangeAns[i].second);
                    }
                }
            } else {
//                std::cout << "-------------------------------------------" << std::endl;
                bottomKNNQuery(queryPoint, radius, kNNRangeAns, *disToCluCenter[index].second);
                // 若数据量小于k，扩大查询半径，这里简单取第二近的簇距离
                if (disToCluCenter.size() > 1) {
                    index++;
                    radius = disToCluCenter[index].first;
                } else {
                    // 处理特殊情况，比如只有一个簇的情况，可以适当增加半径等策略
                    radius *= 2;
                }
            }
        }
        return result;
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void
    bottomKNNQuery(Point<T> &queryPoint, DIS_TYPE query_radius, std::vector<std::pair<DIS_TYPE, OID_TYPE>> &rangeAns,
                   BottomEntry<T> &bottomEntry) {

        Point<T> currentCluCenter = bottomEntry.clusterCenter;
        DIS_TYPE CluCenterRadius = bottomEntry.radius;

        CalCirclePos<DIS_TYPE> refPtCircle(currentCluCenter, CluCenterRadius, queryPoint, query_radius);
        if (refPtCircle.label == 1) {
            return;
        }

        if (refPtCircle.label == 3 && refPtCircle.dis_upper < bottomEntry.dis_lower) {
            return;
        }

        if (refPtCircle.label == 3 && query_radius > bottomEntry.radius) {
            for (auto &a: bottomEntry.objects) {
                DIS_TYPE dist = queryPoint.distance(a);
                rangeAns.emplace_back(dist, a.id);
            }

            return;
        }

        doBottomKNNQuery(bottomEntry, rangeAns, refPtCircle, queryPoint);
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void doBottomKNNQuery(BottomEntry<T> &bottomEntry, std::vector<std::pair<DIS_TYPE, OID_TYPE>> &rangeAns,
                          CalCirclePos<DIS_TYPE> &refPtCircle, Point<T> &queryPoint) {

        int len_dis = bottomEntry.objects.size();

        for (int i = 0; i < len_dis; ++i) {
            DIS_TYPE dis = queryPoint.distance(bottomEntry.clusterCenter);
            if (dis >= refPtCircle.dis_lower && dis <= refPtCircle.dis_upper) {
                rangeAns.emplace_back(dis, bottomEntry.objects[i].id);
            }
        }
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 顺序跟打印底层簇顺序一致
    void ScanBottom(Point<T> &queryPoint, DIS_TYPE query_radius, std::set<OID_TYPE> &scanBottomSet,
                    std::set<OID_TYPE> &scanCluSet) {
        for (int i = 0; i < bottom.bottomEntries.size(); ++i) {
            for (int j = 0; j < bottom.bottomEntries[i].objects.size(); ++j) {
                DIS_TYPE dist = queryPoint.distance(bottom.bottomEntries[i].objects[j]);
                if (dist <= query_radius) {
                    scanCluSet.insert(bottom.bottomEntries[i].clusterCenter.id);
                    scanBottomSet.insert(bottom.bottomEntries[i].objects[j].id);
                }
            }
        }
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void bottomRangeQuery(std::vector<InterSecVector<Key_TYPE>> &aggResult, Point<T> &queryPoint, DIS_TYPE query_radius,
                          std::set<OID_TYPE> &rangeAns, std::vector<OID_TYPE> &rangeAnsVector) {

        for (const auto &element: aggResult) {
            for (auto &object: element.bottomEntry->objects) {
                DIS_TYPE dis = queryPoint.distance(object);
                if (dis <= query_radius) {
                    rangeAns.insert(object.id);
                    rangeAnsVector.push_back(object.id);
                }
            }
        }
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void doBottomRangeQuery(BottomEntry<T> *bottomEntry, std::set<OID_TYPE> &rangeAns,
                            CalCirclePos<DIS_TYPE> &refPtCircle, Point<T> &queryPoint, DIS_TYPE query_radius) {

        // 使用 std::lower_bound 查找第一个不小于 refPtCircle.dis_lower 的位置
        auto it_lower = std::lower_bound(bottomEntry->dis.begin(), bottomEntry->dis.end(), refPtCircle.dis_lower);
        auto it_upper = std::lower_bound(bottomEntry->dis.begin(), bottomEntry->dis.end(), refPtCircle.dis_upper);

        int lower_index = std::distance(bottomEntry->dis.begin(), it_lower);
        int upper_index = std::distance(bottomEntry->dis.begin(), it_upper);

        for (int i = lower_index; i <= upper_index; ++i) {
            if (bottomEntry->objects[i].distance(queryPoint) <= query_radius) {
                rangeAns.insert(bottomEntry->objects[i].id);
            }
        }
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void upperRangeQuery(Point<T> &queryPoint, DIS_TYPE query_radius, UpperEntry<T> &upperEntry,
                         std::vector<InterSecVector<Key_TYPE>> &PerRangeQuery,
                         CalCirclePos<DIS_TYPE> &refPtCircle, std::set<OID_TYPE> &rangeAnsSet, std::ostream &outFile) {

//        std::chrono::steady_clock::time_point time_begin;
//        std::chrono::steady_clock::time_point time_end;
//
//        time_begin = std::chrono::steady_clock::now();
        DIS_TYPE target_dis_lower = refPtCircle.dis_lower;
//        DIS_TYPE target_dis_upper = refPtCircle.dis_upper;
//        outFile << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
//        outFile << "两圆位置关系----下限: " << target_dis_lower << "; 上限: " << target_dis_upper << std::endl;
//        outFile << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        double RefPre_disLower = upperEntry.coefficients_upper[0];
//        double RefPre_disUpper = upperEntry.coefficients_lower[0];
        for (int i = 1; i <= COEFFICIENTS; ++i) {
            RefPre_disLower += upperEntry.coefficients_upper[i] * pow(target_dis_lower, i);
//            RefPre_disUpper += upperEntry.coefficients_lower[i] * pow(target_dis_upper, i);
        }

        // 取整
        int RefPrePos_lower = static_cast<int>(RefPre_disLower);
//        int RefPrePos_upper = static_cast<int>(RefPre_disUpper);

        int len_dis = upperEntry.bottomEntryByMinDisToPivot.size();

        if (RefPrePos_lower < 0)
            RefPrePos_lower = 0;
        if (RefPrePos_lower >= len_dis)
            RefPrePos_lower = len_dis - 1;

        int pred_lower = 0;
        if (upperEntry.dis_upper[RefPrePos_lower] == target_dis_lower) {
            pred_lower = RefPrePos_lower;
        } else if (upperEntry.dis_upper[RefPrePos_lower] > target_dis_lower) {
            pred_lower = DoublingSearch(upperEntry.dis_upper, true, target_dis_lower, RefPrePos_lower);
        } else {
            pred_lower = DoublingSearch(upperEntry.dis_upper, false, target_dis_lower, RefPrePos_lower);
        }

        // 找到首个不小于下限的索引位置
        if (upperEntry.dis_upper[pred_lower] >= target_dis_lower)
            pred_lower = pred_lower;
        else
            pred_lower = (pred_lower + 1);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//        if (RefPrePos_upper < 0)
//            RefPrePos_upper = 0;
//        if (RefPrePos_upper >= len_dis)
//            RefPrePos_upper = len_dis - 1;
//
//        int pred_upper = 0;
//        if (upperEntry.dis_lower[RefPrePos_upper] == target_dis_upper) {
//            pred_upper = RefPrePos_upper;
//        } else if (upperEntry.dis_lower[RefPrePos_upper] > target_dis_upper) {
//            pred_upper = DoublingSearch(upperEntry.dis_lower, true, target_dis_upper, RefPrePos_upper);
//        } else {
//            pred_upper = DoublingSearch(upperEntry.dis_lower, false, target_dis_upper, RefPrePos_upper);
//        }
//
//        if (upperEntry.dis_lower[pred_upper] > target_dis_upper)
//            pred_upper = (pred_upper - 1);
//        else
//            pred_upper = pred_upper;

//        time_end = std::chrono::steady_clock::now();
////
//        std::cout << " 相交时，采用最大距离数组的单个模型【预测】耗时: "
//                  << chrono::duration_cast<chrono::nanoseconds>(time_end - time_begin).count() << " [ns]"
//                  << endl;

//        std::vector<BottomEntry<T> *> destBottomEntryByMinDisToPivot(upperEntry.bottomEntryByMinDisToPivot.begin(),
//                                                                     upperEntry.bottomEntryByMinDisToPivot.begin() +
//                                                                     pred_upper + 1);

//        std::vector<BottomEntry<T> *> destBottomEntryByMaxDisToPivot(
//                upperEntry.bottomEntryByMaxDisToPivot.begin() + pred_lower,
//                upperEntry.bottomEntryByMaxDisToPivot.end());

        // 将vector转换为set
//        std::set<BottomEntry<T> *> set1(destBottomEntryByMinDisToPivot.begin(), destBottomEntryByMinDisToPivot.end());
//        std::set<BottomEntry<T> *> set2(destBottomEntryByMaxDisToPivot.begin(), destBottomEntryByMaxDisToPivot.end());

        // 创建一个set来存储交集
//        std::set<BottomEntry<T> *> intSec;
//
//        // 使用std::set_intersection算法计算交集
//        std::set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(),
//                              std::inserter(intSec, intSec.begin()));
//
//        outFile << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
//        outFile << "下限: " << pred_lower << "; 上限: " << pred_upper << "; 交集大小:" << intSec.size() << std::endl;
//        outFile << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//        outFile << "MinMax 交集 ID 及 实际相交的 ID： " << std::endl;

//        time_begin = std::chrono::steady_clock::now();
        for (int i = pred_lower; i < upperEntry.bottomEntryByMaxDisToPivot.size(); ++i) {
//            outFile << std::setw(10) << elem->clusterCenter.id << "\t";

            CalCirclePos<DIS_TYPE> refPCir(upperEntry.bottomEntryByMaxDisToPivot[i]->clusterCenter,
                                           upperEntry.bottomEntryByMaxDisToPivot[i]->radius, queryPoint, query_radius);

            if (refPCir.label == 2) {
//                outFile << "与该簇相交: " << std::setw(10) << elem->clusterCenter.id << "\t" << elem << std::endl;

//                PerRangeQuery.emplace_back(elem->clusterCenter.id, refPCir.dis_lower, refPCir.dis_upper, elem);

                for (auto &object: upperEntry.bottomEntryByMaxDisToPivot[i]->objects) {
                    DIS_TYPE dis = queryPoint.distance(object);
                    if (dis <= query_radius) {
                        rangeAnsSet.insert(object.id);
                    }
                }

            } else if (refPCir.label == 3 && upperEntry.bottomEntryByMaxDisToPivot[i]->radius <= query_radius) {
//                outFile << "查询圆完全包含所有" << std::endl;
//                PerRangeQuery.emplace_back(elem->clusterCenter.id, refPCir.dis_lower, refPCir.dis_upper, elem);

                for (int j = 0; j < upperEntry.bottomEntryByMaxDisToPivot[i]->objects.size(); j++) {
                    rangeAnsSet.insert(upperEntry.bottomEntryByMaxDisToPivot[i]->objects[j].id);
                }
            } else {
//                outFile << "不相交" << std::endl;
            }
        }

//        time_end = std::chrono::steady_clock::now();
//        std::cout << "扫描区间[pre_upper,末尾]，判断相交或完全包围收集结果耗时: "
//                  << chrono::duration_cast<chrono::microseconds>(time_end - time_begin).count() << " [µs]"
//                  << endl;

//        outFile << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//        if (pred_lower < len_dis && pred_upper < len_dis && pred_lower <= pred_upper) {
//
//            for (size_t i = pred_lower; i <= pred_upper; ++i) {
//                CalCirclePos<DIS_TYPE> refPCircle(upperEntry.bottomEntryByMinDisToPivot[i]->clusterCenter,
//                                                  upperEntry.bottomEntryByMinDisToPivot[i]->radius, queryPoint,
//                                                  query_radius);
//
//                if (refPCircle.label == 2) {
//                    PerRangeQuery.emplace_back(upperEntry.bottomEntryByMinDisToPivot[i]->clusterCenter.id,
//                                               upperEntry.bottomEntryByMinDisToPivot[i]);
//                } else if (refPCircle.label == 3 &&
//                           upperEntry.bottomEntryByMinDisToPivot[i]->radius < query_radius) {
//                    for (auto a: upperEntry.bottomEntryByMinDisToPivot[i]->objects) {
//                        rangeAns.insert(a.id);
//                    }
//                }
//            }
//        }
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /* 指数搜索
     * param 1 : list
     * param 2 : search forward(true) / search backward(false)
     * param 3 : target value
     */
    int DoublingSearch(vector<double> &disList, bool flag, double target, int start) {
        uint64_t len = disList.size();
        if (flag) {
            if (start == 0)
                return 0;
            int k = 1;
            int end = start;
            while (disList[end] > target) {
                start = end;
                end -= k;
                k = k << 1;
                if (end < 0) {
                    end = 0;
                    break;
                }
            }
            if (disList[end] == target)
                return end;
            if (start == end && start == 0)
                return 0;
            return BinarySearchForDoubling(disList, target, end, start);
        } else {
            if (start == len - 1)
                return len - 1;
            int k = 1;
            int end = start;
            while (disList[end] < target) {
                start = end;
                end += k;
                k = k << 1;
                if (end > len - 1) {
                    end = len - 1;
                    break;
                }
            }
            if (disList[end] == target)
                return end;
            if (start == end && start == len - 1)
                return len - 1;

            return BinarySearchForDoubling(disList, target, start, end);
        }
    }

    int BinarySearchForDoubling(vector<double> &disList, double target, int low, int high) {
        int middle = 0;
        while (low <= high) {
            middle = (high - low) / 2 + low;
            if (target < disList[middle]) {
                high = middle - 1;
            } else if (target > disList[middle]) {
                low = middle + 1;
            } else {
                if ((middle > 0 && disList[middle - 1] < target) || (middle == 0))//找到开始位置
                {
                    break;
                } else
                    high = middle - 1;
            }
        }
        return middle;
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    std::vector<Point<T>> getBottomClusterCenter() {
        std::vector<Point<T>> bottomClusterCenter;
        for (const auto &bottomEntry: bottom.bottomEntries) {
            bottomClusterCenter.push_back(bottomEntry.clusterCenter);
        }

        return bottomClusterCenter;
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void getBottom(std::vector<BottomEntry<T> *> &bottomCluster) {
        for (int i = 0; i < bottom.bottomEntries.size(); ++i) {
            bottomCluster.push_back(&bottom.bottomEntries[i]);
        }
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void getBottomPointsSize(std::set<Point<T>> &bottomPoints, std::vector<Point<Key_TYPE>> &vecBottomPoints) {
        for (const auto &bottomEntry: bottom.bottomEntries) {
            for (const auto &bottomPoint: bottomEntry.objects) {
                bottomPoints.insert(bottomPoint);
                vecBottomPoints.push_back(bottomPoint);
            }
        }
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void buildTwoLayerIndex(HuffmanTree<T> &huffmanTree, std::vector<TempNode<T>> &results) {

        // 遍历排序后的内节点信息,按照规则构建底层节点集合
        for (const auto &item: results) {
            HuffmanTreeNode<T> *currentNode = item.huffmanTreeNode;

            std::vector<Point<T>> leafPoints;
            huffmanTree.collectLeafPoints(currentNode, leafPoints);
            BottomEntry<T> newBottomEntry(currentNode->point, leafPoints);
            bottom.bottomEntries.push_back(newBottomEntry);
        }

        std::sort(results.begin(), results.end(), TempNode<T>::compareByLevelAndLeafCount);

        std::vector<BottomEntry<T> *> bottomCluster;
        getBottom(bottomCluster);

        for (int i = 0; i < PIVOT_NUM; ++i) {
            UpperEntry<T> newUpperEntry(results[i].huffmanTreeNode->point, bottomCluster);
            upper.upperEntries.push_back(newUpperEntry);
        }
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 以表格形式输出底层节点关键信息（如序号、叶节点数量、包围半径等）的函数
    void printBottomNodesInTableFormat() {
        std::ofstream outFile("../../results/msli/BottomNodes.txt");
        if (outFile.is_open()) {
            outFile << std::fixed << std::setprecision(6);

            outFile << std::setw(10) << "底层簇 ID\t\t" << std::setw(10) << "簇包围的数据点\t\t" << std::setw(10)
                    << "包围半径\t\t半径下限" << std::endl;

            for (size_t i = 0; i < bottom.bottomEntries.size(); ++i) {
                const auto &entry = bottom.bottomEntries[i];
                outFile << std::setw(10) << entry.clusterCenter.id << "\t\t" << std::setw(10) << entry.objects.size()
                        << "\t\t" << std::setw(10) << entry.radius << "\t\t" << std::setw(10) << entry.dis_lower
                        << std::endl;
            }

            outFile << "*****************************************************************************" << std::endl;
            outFile.close();
        } else {
            std::cerr << "无法打开文件: " << "../../results/msli/BottomNodes.txt" << " 进行写入。" << std::endl;
        }
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void printUpperNodesInTableFormat(std::ostream &outFile) {
        outFile << std::fixed << std::setprecision(6);
        outFile << std::setw(10) << "枢轴点ID\t\t\t" << std::setw(10) << "最小半径\t\t\t" << std::setw(10)
                << "最大半径" << std::endl;

        for (size_t i = 0; i < upper.upperEntries.size(); ++i) {
            const auto &entry = upper.upperEntries[i];
            outFile << std::setw(10) << entry.pivotPoint.id << "\t\t" << std::setw(10) << entry.minDistToPivot
                    << "\t\t" << std::setw(10) << entry.maxDistToPivot << std::endl;
        }
    }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
